<template>
    <div style="margin: 15px 0">
        <a-space>
            域名/网站id
            <a-select style="width: 90px" v-model:value="searchField2" :options="searchFieldOptions2"></a-select>
            <a-textarea v-model:value="searchValue2" :rows="1" style="width: 200px" placeholder="搜索域名/id多个换行">
            </a-textarea>
            关键词
            <a-select style="width: 90px" v-model:value="searchField" :options="searchFieldOptions"></a-select>
            <a-textarea v-model:value="searchValue" :rows="1" style="width: 200px" placeholder="关键词 ... 多个换行">
            </a-textarea>
            <a-button type="primary" style="width: 100px" @click="searchFunc">
                <template #icon>
                    <SearchOutlined />
                </template>
                搜索
            </a-button>
            <a-button type="dashed" @click="addWebsiteKeyword"> 添加 </a-button>
            <a-popconfirm title="是否删除已选中的链接？" ok-text="确定" cancel-text="取消" @confirm="deleleWebsiteInfo">
                <a-button type="dashed" danger style="margin-left: 10px">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除</a-button
                >
            </a-popconfirm>
        </a-space>
    </div>
    <KeywordDensityAddOrUpdateComponent v-model:visible="addOrUpdateVisible" :current-row="currentRow" />
    <a-spin :style="spinStyle" :spinning="tableLoading">
        <a-table
            sticky
            :scroll="{ x: 1700 }"
            :row-selection="rowSelection"
            :rowKey="(row: any) => JSON.stringify(row)"
            :columns="columns"
            :data-source="tableData"
            bordered
            :pagination="false"
            size="small"
            @change="handleTableChange"
            class="table"
        >
        </a-table>
        <a-row justify="center" v-if="total > 10" style="margin-top: 10px">
            <a-pagination
                v-model:current="page"
                v-model:pageSize="size"
                show-quick-jumper
                showSizeChanger
                :total="total"
                :page-size-options="pageSizeOptions"
                @change="pageChange"
                :show-total="(total: number) => `总计 ${total} 项`"
            />
        </a-row>
    </a-spin>
</template>

<script lang="ts" setup>
    import { useGetWebsiteIds, useSpinLoadingState } from "@/hooks/useCommon";
    import { useColumns } from "@/hooks/useWebsiteKeyword";
    import { websiteKeywordsApi } from "@/api/esArticle";
    import { SearchOutlined, DeleteOutlined } from "@ant-design/icons-vue";
    import { message } from "ant-design-vue";
    import { KeywordDensityAddOrUpdateComponent } from "./tsx/keywordDensity";
    const { columns, isReloadData, addOrUpdateVisible, currentRow } = useColumns();
    const { spinStyle, viewLoading: tableLoading } = useSpinLoadingState();
    const pageSizeOptions = ref<string[]>(["10", "20", "50", "100", "500", "1000"]);
    const searchFieldOptions2 = [
        {
            label: "网站ID",
            value: "webid"
        },
        {
            label: "域名",
            value: "pc_domain"
        }
    ];
    // webid | pc_domain
    const searchField2 = ref("pc_domain");
    const searchValue2 = ref("");
    const searchValue = ref("");
    const searchField = ref("subject");
    const searchFieldOptions = [
        {
            label: "主词",
            value: "subject"
        },
        {
            label: "长尾词",
            value: "long_tailed_word"
        },
        {
            label: "相关词",
            value: "related_words"
        }
    ];
    // 查询总数
    const total = ref(0);
    // 表格数据
    const tableData = ref([]);
    const page = ref(1);
    const size = ref(10);
    // 收集行key
    const selectedRowKeys = ref<Array<number>>([]);
    const sortObj = reactive({ order: "", sort_field: "" });
    // 表格排序发生改变
    const handleTableChange = (pag: any, filters: any, sorter: any) => {
        if (sorter.order) {
            sortObj.order = sorter.order.slice(0, sorter.order.length - 3);
            sortObj.sort_field = sorter.field;
        } else {
            sortObj.order = "";
        }
        searchFunc();
    };
    // 行Key
    const rowSelection = ref<any>({
        checkStrictly: false,
        onSelect: (_: boolean, __: boolean, selectedRows: Array<Record<string, any>>) => {
            selectedRowKeys.value = selectedRows.map((item) => item["id"]);
        },
        onSelectAll: (_: boolean, __: boolean, selectedRows: Array<Record<string, any>>) => {
            selectedRowKeys.value = selectedRows.map((item) => item["id"]);
        }
    });
    // 搜索
    const searchFunc = () => {
        tableLoading.value = true;
        // 搜索的条件
        const params = {
            page: page.value,
            page_size: size.value,
            pc_domain: "",
            order: sortObj.order,
            search: searchValue.value,
            order_field: sortObj.sort_field,
            search_field: searchField.value,
            ids: ""
        };
        const str = JSON.stringify(searchValue2.value.split("\n").filter(Boolean));
        if (searchField2.value === "webid") {
            params.ids = str;
            Reflect.deleteProperty(params, "pc_domain");
        } else {
            params.pc_domain = str;
            Reflect.deleteProperty(params, "ids");
        }
        websiteKeywordsApi("get", params)
            .then((res) => {
                tableData.value = res.data.data;
                total.value = res.data.count;
            })
            .catch(() => message.error("超时！"))
            .finally(() => {
                isReloadData.value = false;
                tableLoading.value = false;
            });
    };
    // 页码更新
    const pageChange = (pageNumber: number) => {
        page.value = pageNumber;
        searchFunc();
    };
    // 添加关键词和网站信息
    const addWebsiteKeyword = () => {
        addOrUpdateVisible.value = true;
        // @ts-ignore
        currentRow.value = null;
    };
    // 删除网站信息
    const deleleWebsiteInfo = () => {
        if (selectedRowKeys.value.length <= 0) {
            message.error("请勾选删除的网站信息！");
            return;
        }
        websiteKeywordsApi("delete", { ids: selectedRowKeys.value })
            .then(() => {
                isReloadData.value = true;
                message.success("操作成功!");
            })
            .catch(() => {
                message.error("操作失败!");
            });
    };
    provide("isReloadData", isReloadData);
    watch(isReloadData, (v) => {
        v && setTimeout(searchFunc, 200);
    });
    onMounted(async () => {
        // 延迟
        const route = useRoute();
        const ids = JSON.parse((route.query.ids || "[]") as string);
        if (ids.length) {
            searchField2.value = "webid";
            searchValue2.value = ids.join("\n");
        } else if (route.query.query) {
            searchField2.value = "webid";
            const ids = await useGetWebsiteIds(JSON.parse(route.query.query as string));
            searchValue2.value = ids.join("\n");
        }
        searchFunc();
    });
</script>

<style scoped lang="scss"></style>
